import React, { useState, useEffect } from 'react';
import {Form, Input, Button, Card, message, Space, Typography, Image} from 'antd';
import { MobileOutlined, LockOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import {Link, useNavigate} from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { setCredentials } from '../../store/slices/authSlice';
import { login, getCaptcha } from '../../api/auth';

interface LoginResponse {
  token: string;
  user: {
    id: number;
    nick_name?: string;
    nickname?: string;
    userName?: string;
    username?: string;
    role: number;
    expired_at: number;
  };
}

interface LoginForm {
  mobile: string;
  password: string;
  captcha: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [captchaImage, setCaptchaImage] = useState<string>('');
  const [captchaId, setCaptchaId] = useState<string>('');

  const refreshCaptcha = async () => {
    try {
      const { captchaId, picPath } = await getCaptcha();
      setCaptchaId(captchaId);
      setCaptchaImage(picPath);
    } catch (error) {
      console.error('Failed to fetch captcha:', error);
      message.error('获取验证码失败，请重试');
    }
  };

  useEffect(() => {
    refreshCaptcha();
  }, []);

  const onFinish = async (values: LoginForm) => {
    try {
      console.log('Login attempt with:', {
        mobile: values.mobile,
        captcha_id: captchaId,
        timestamp: new Date().toISOString()
      });

      const response = await login({
        mobile: values.mobile,
        password: values.password,
        captcha: values.captcha,
        captcha_id: captchaId
      }) as LoginResponse;

      // 记录原始响应数据（不包含敏感信息）
      console.log('Login API response received:', {
        hasToken: !!response?.token,
        hasUser: !!response?.user,
        responseStructure: Object.keys(response || {}),
        timestamp: new Date().toISOString()
      });

      // 验证响应数据的完整性
      if (!response) {
        throw new Error('登录响应为空');
      }

      if (!response.token) {
        throw new Error('登录响应中缺少token');
      }

      if (!response.user) {
        throw new Error('登录响应中缺少用户信息');
      }

      if (typeof response.user.role !== 'number') {
        console.warn('用户角色信息格式不正确:', response.user.role);
      }

      // 直接将原始响应传递给 Redux
      // 这样可以确保所有字段都被正确处理，包括 role 和 expired_at
      dispatch(setCredentials(response));

      console.log('Login successful, navigating to dashboard');
      message.success('登录成功');
      navigate('/dashboard');
    } catch (error: any) {
      console.error('Login error:', error);

      // 显示后端返回的具体错误信息
      if (error.response && error.response.data) {
        const errorData = error.response.data;
        // 检查错误数据的格式并提取错误信息
        if (typeof errorData === 'object' && errorData !== null) {
          const errorMessages = Object.values(errorData).filter(Boolean).join(', ');
          message.error(errorMessages || '登录失败，请稍后重试');
        } else if (typeof errorData === 'string') {
          message.error(errorData);
        } else {
          message.error('登录失败，请稍后重试');
        }
      } else if (error instanceof Error) {
        message.error(error.message || '登录失败，请稍后重试');
      } else {
        message.error('登录失败，请稍后重试');
      }

      // 如果是验证码错误，自动刷新验证码
      if (error.response?.data?.captcha) {
        refreshCaptcha();
      }
    }
  };
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh',
      background: '#f0f2f5'
    }}>
      <Typography.Title level={2} style={{ marginBottom: '2rem', textAlign: 'center' }}>
        多语言切换管理系统
      </Typography.Title>
      <Card
        title={<div style={{ width: '100%', textAlign: 'center' }}>登录</div>}
        style={{ width: 300 }}
      >
        <Form
          name="login"
          initialValues={{ remember: true }}
          onFinish={onFinish}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号!' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号!' }
            ]}
          >
            <Input
              prefix={<MobileOutlined />}
              placeholder="手机号"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="密码"
            />
          </Form.Item>

          <Form.Item>
            <div style={{ display: 'flex', marginBottom: '16px' }}>
              <Image
                src={captchaImage}
                alt="验证码"
                preview={false}
                style={{ height: '40px', marginRight: '8px' }}
                onClick={refreshCaptcha}
              />
              <Form.Item
                name="captcha"
                noStyle
                rules={[{ required: true, message: '请输入验证码!' }]}
              >
                <Input
                  prefix={<SafetyCertificateOutlined />}
                  placeholder="验证码"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </div>
          </Form.Item>

          <Form.Item>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
                登录
              </Button>
              <div style={{ textAlign: 'center' }}>
                还没有账号？<Link to="/register">立即注册</Link>
              </div>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;